<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="operationUserName">
        <el-input
          v-model="queryParams.operationUserName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
        >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:operation:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:operation:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:operation:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['device:operation:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column
        label="运维人员编号"
        align="center"
        prop="operationUserCode"
        width="190"
      />
      <el-table-column label="姓名" align="center" prop="operationUserName"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scoped">
          {{ scoped.row.sex === "0" ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phoneNumber"/>
      <el-table-column label="邮箱" align="center" prop="email" width="200"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:operation:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:operation:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运维人员信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="运维人员编号" prop="operationUserCode" v-if="form.id">
          <el-input v-model="form.operationUserCode" disabled/>
        </el-form-item>
        <el-form-item label="姓名" prop="operationUserName">
          <el-input v-model="form.operationUserName" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" maxlength="11" show-word-limit/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!--  删除失败提示-->
    <el-dialog
      :visible.sync="deleteFailedDialogVisible"
      top="100px !important"
      width="800px"
      :close-on-click-modal="false"
      z-index="1002"
    >
      <template slot="title">
        提示：<span class="tip" style="color: red">运维人员被以下设备部署引用，若要删除，请先从设备部署管理界面修改为其他的运维人员！</span>
      </template>
      <el-table :data="userInUsedList" max-height="600px">
        <el-table-column property="deviceId" label="设备ID" align="center" width="190"/>
        <el-table-column property="deviceName" label="设备部署名称" align="center"/>
        <el-table-column property="deleteOperationUserCode" label="引用运维人员编号" align="center" width="190"/>
        <el-table-column property="deleteOperationUserName" label="引用运维人员姓名" align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="navToPlaceManagerUnbind(scope.row)">去解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteFailedDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOperationUser,
  getOperationUser,
  addOperationUserr,
  updateOperationUser,
  delOperationUser
} from "@/api/device/operationUser";
import {handleAESDecrypt} from '@/utils/ase'

export default {
  name: "Operation",
  data() {
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运维人员信息表格数据
      userList: [],
      // 正常运维人员所有信息,0为正常
      operationUserAllList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        operationUserCode: null,
        operationUserName: null,
        sex: null,
        phoneNumber: null,
        email: null,
        status: 0,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        operationUserName: [{required: true, message: "运维人员姓名不能为空", trigger: "blur"}],
        phoneNumber: [
          {required: true, message: "手机号码不能为空", trigger: "blur"},
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ],
        sex: [
          {required: true, message: "性别不能为空", trigger: "blur"},
        ],
        email: [
          {required: true, validator: checkEmail, triggle: "blur"},
        ],
      },
      sexs: [
        {id: 1, value: '0', label: '男'},
        {id: 2, value: '1', label: '女'}
      ],
      deleteFailedDialogVisible: false,
      userInUsedList: []
    };
  },
  methods: {
    // 跳转到设备部署管理页面解绑
    navToPlaceManagerUnbind(row) {
      this.deleteFailedDialogVisible = false;
      this.$router.push({
        name: 'PlaceManager',
        query: {operationUserName: row.operationUserName}
      })
    },
    /** 查询运维人员信息列表 */
    getList() {
      this.loading = true;
      listOperationUser(this.queryParams).then((response) => {
        // 是否已经加载过设备列表标记改为true
        if (!this.alreadyGetList) this.alreadyGetList = true;
        this.userList = response.rows;
        var reg = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 ，判断正整数用/^[1-9]+[0-9]*]*$/
        var emailReg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        this.userList.forEach(item => {
          item.operationUserName = handleAESDecrypt(item.operationUserName
          )
          if (item.phoneNumber && !reg.test(item.phoneNumber
          )) {
            item.phoneNumber = handleAESDecrypt(item.phoneNumber)
          }
          if (item.email && !emailReg.test(item.email
          )) {
            item.email = handleAESDecrypt(item.email)
          }
        })
        console.log(this.userList, 'this.userList')
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        operationUserCode: null,
        operationUserName: null,
        sex: null,
        phoneNumber: null,
        email: null,
        status: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.operationUserName = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加运维人员信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOperationUser(id).then((response) => {
        this.form = response.data;
        var reg = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 ，判断正整数用/^[1-9]+[0-9]*]*$/
        var emailReg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        for (let value in this.form) {
          if (value == 'operationUserName' && this.form[value]) {
            this.form[value] = handleAESDecrypt(this.form[value])

          }
          if (value == 'phoneNumber' && this.form[value] && !reg.test(this.form[value])) {
            this.form[value] = handleAESDecrypt(this.form[value])

          }
          if (value == 'email' && this.form[value] && !emailReg.test(this.form[value])) {
            this.form[value] = handleAESDecrypt(this.form[value])

          }
        }
        this.open = true;
        this.title = "修改运维人员信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOperationUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              //更新保存在vuex的运维人员信息
              this.$store.dispatch('LoadOperationUserOption');
            });
          } else {
            addOperationUserr(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              //更新保存在vuex的运维人员信息
              this.$store.dispatch('LoadOperationUserOption');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除运维人员信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOperationUser(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          //更新保存在vuex的运维人员信息
          this.$store.dispatch('LoadOperationUserOption');
        })
        .catch((res) => {
          this.loading = false;
          const list = res.data;
          if (list.length) {
            this.userInUsedList = list;
            this.deleteFailedDialogVisible = true;
          }
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      this.download('device/operationUser/export', {
        ...this.queryParams
      }, `运维人员信息_${currentDate}.xlsx`)
    }
  },
  beforeRouteEnter(to, from, next) {
    const {operationUserName} = to.query;
    // 如果存在跳转参数operationUserName,自动填入查询条件
    if (operationUserName) {
      next(vm => {
        vm.resetForm("queryForm");
        vm.queryParams.operationUserName = operationUserName;
        vm.getList();
      })
    } else {  // 不存在查询参数
      next(vm => {
        // 是否已加载过列表，第一次进入才调用获取列表接口
        if (!vm.alreadyGetList) {
          vm.getList();
        }
      });
    }
  },
  /*  在离开页面时清空跳转携带的参数 暂时不用
    beforeRouteLeave(to, from, next) {
      // 如果当前路由存在operationUserName参数，跳转前清空参数
      if (this.$route.query.operationUserName) {
        this.queryParams.operationUserName = null;
        // 重新加载列表
        this.getList();
      }
      next();
    },*/
};
</script>
